package com.ronglian.register_mini_program.controller;

import com.ronglian.register_mini_program.model.*;
import com.ronglian.register_mini_program.model.dto.ActivityDto;
import com.ronglian.register_mini_program.model.dto.UserDto;
import com.ronglian.register_mini_program.model.web.ActivityDetailBody;
import com.ronglian.register_mini_program.model.web.PageResult;
import com.ronglian.register_mini_program.result.ResultBody;
import com.ronglian.register_mini_program.service.*;
import com.ronglian.register_mini_program.util.DateUtil;
import com.ronglian.register_mini_program.util.PageResultUtil;
import io.swagger.annotations.*;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/activity")
@Api(tags = "创建活动管理", description = "创建活动管理")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful — 请求已完成"),
        @ApiResponse(code = 400, message = "请求中有语法问题，或不能满足请求"),
        @ApiResponse(code = 401, message = "未授权客户机访问数据"),
        @ApiResponse(code = 404, message = "服务器找不到给定的资源；文档不存在"),
        @ApiResponse(code = 500, message = "服务器不能完成请求")}
)
public class ActivityController {
    @Autowired
    RegisterService registerService;
    @Autowired
    ActivityService activityService;
    @Autowired
    TypeService typeService;
    @Autowired
    OrderService orderService;
    @Autowired
    UserService userService;

    @ApiOperation(value = "创建活动", notes = "创建活动")
    @ApiImplicitParam(paramType = "body", dataType = "ActivityDto", name = "param", value = "信息参数", required = true)
    @RequestMapping(value = "/createActivity", method = RequestMethod.POST)
    public ResultBody createActivity(@RequestBody ActivityDto activity) {
        try {
            if (activity == null) {
                return new ResultBody("500", "参数为空！");
            }
            if (StringUtils.isBlank(activity.getStart_time()) || StringUtils.isBlank(activity.getEnd_time()) || StringUtils.isBlank(activity.getActivity_mark()) || StringUtils.isBlank(activity.getActivity_postion()) || StringUtils.isBlank(activity.getActivity_title()) || StringUtils.isBlank(activity.getRequired_info())) {
                return new ResultBody("500", "请完善活动信息！");
            }
            //判断传输的时间格式是否正确
            long start_time = DateUtil.strToDateMiddle(activity.getStart_time()).getTime();
            long end_time = DateUtil.strToDateMiddle(activity.getEnd_time()).getTime();


            if (end_time <= start_time) {
                return new ResultBody("500", "该活动开始截至时间填写不正确！");
            }


            RegisterActivityWithBLOBs ra = new RegisterActivityWithBLOBs();

            ra.setActivity_background_url(activity.getActivity_background_url());
            ra.setActivity_detail_url(activity.getActivity_detail_url());
            ra.setActivity_icon_url(activity.getActivity_icon_url());
            ra.setActivity_image_url(activity.getActivity_image_url());
            ra.setActivity_mark(activity.getActivity_mark());

            ra.setActivity_id(activity.getActivity_id());
            ra.setActivity_postion(activity.getActivity_postion());
            ra.setActivity_title(activity.getActivity_title());
            ra.setCount(activity.getCount());
            if (activity.getCreate_time() != null) {

                ra.setCreate_time(DateUtil.strToDateLong(activity.getCreate_time()));
            }


            if (activity.getEnd_time() != null) {
                ra.setEnd_time(DateUtil.strToDateMiddle(activity.getEnd_time()));
            }

            ra.setIs_alive(1);
            ra.setIs_limit(activity.getIs_limit());
            ra.setLimit_number(activity.getLimit_number());
            ra.setRequired_info(activity.getRequired_info());
            ra.setSponsor_id(activity.getSponsor_id());
            if (activity.getStart_time() != null) {
                System.out.println("报名开始时间" + DateUtil.strToDateMiddle(activity.getStart_time()));
                ra.setStart_time(DateUtil.strToDateMiddle(activity.getStart_time()));
            }

            ra.setTicket_type(activity.getTicket_type());
            ra.setType(activity.getType());
            if (activity.getUpdate_time() != null) {
                ra.setUpdate_time(DateUtil.strToDateLong(activity.getUpdate_time()));
            }

            activityService.insert(ra);
            return new ResultBody(ra);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "创建活动失败！");
        }

    }


    @ApiOperation(value = "修改活动", notes = "修改活动")
    @ApiImplicitParam(paramType = "body", dataType = "ActivityDto", name = "param", value = "信息参数", required = true)
    @RequestMapping(value = "/updateActivity", method = RequestMethod.POST)
    public ResultBody updateActivity(@RequestBody ActivityDto activity) {
        //修改活动信息，还应该修改，arrange中的上课 吃饭 睡觉
        try {
            if (activity == null) {
                return new ResultBody("500", "参数为空！");
            }
            if (StringUtils.isBlank(activity.getStart_time()) || StringUtils.isBlank(activity.getEnd_time()) || StringUtils.isBlank(activity.getActivity_mark()) || StringUtils.isBlank(activity.getActivity_postion()) || StringUtils.isBlank(activity.getActivity_title()) || StringUtils.isBlank(activity.getRequired_info())) {
                return new ResultBody("500", "请完善活动信息！");
            }
            //判断传输的时间格式是否正确
            long start_time = DateUtil.strToDateMiddle(activity.getStart_time()).getTime();
            long end_time = DateUtil.strToDateMiddle(activity.getEnd_time()).getTime();


            if (end_time <= start_time) {
                return new ResultBody("500", "该活动开始截至时间填写不正确！");
            }
            RegisterActivityWithBLOBs ra = new RegisterActivityWithBLOBs();
            ra.setActivity_background_url(activity.getActivity_background_url());
            ra.setActivity_detail_url(activity.getActivity_detail_url());
            ra.setActivity_icon_url(activity.getActivity_icon_url());
            ra.setActivity_image_url(activity.getActivity_image_url());
            ra.setActivity_mark(activity.getActivity_mark());

            ra.setActivity_id(activity.getActivity_id());
            ra.setActivity_postion(activity.getActivity_postion());
            ra.setActivity_title(activity.getActivity_title());
            ra.setCount(activity.getCount());
            if (activity.getCreate_time() != null) {

                ra.setCreate_time(DateUtil.strToDateLong(activity.getCreate_time()));
            }


            if (activity.getEnd_time() != null) {
                ra.setEnd_time(DateUtil.strToDateMiddle(activity.getEnd_time()));
            }

            ra.setIs_alive(1);
            ra.setIs_limit(activity.getIs_limit());
            ra.setLimit_number(activity.getLimit_number());
            ra.setRequired_info(activity.getRequired_info());
            ra.setSponsor_id(activity.getSponsor_id());
            if (activity.getStart_time() != null) {
                System.out.println("报名开始时间" + DateUtil.strToDateMiddle(activity.getStart_time()));
                ra.setStart_time(DateUtil.strToDateMiddle(activity.getStart_time()));
            }

            ra.setTicket_type(activity.getTicket_type());
            ra.setType(activity.getType());
            if (activity.getUpdate_time() != null) {
                ra.setUpdate_time(DateUtil.strToDateLong(activity.getUpdate_time()));
            }

            activityService.update(ra);
            return new ResultBody(ra);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "修改活动失败!");
        }

    }

    @ApiOperation(value = "删除活动", notes = "删除活动")
    @ApiImplicitParam(paramType = "path", name = "activity_id", value = "活动id",
            required = true, dataType = "Integer")
    @RequestMapping(value = "/deleteActivity/{activity_id}", method = RequestMethod.GET)
    public ResultBody deleteActivity(@PathVariable("activity_id") Integer activity_id) {
        try {
            activityService.delete(activity_id);
            return new ResultBody();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "删除活动失败！");
        }

    }

    @ApiOperation(value = "分页获取用户本人发起的活动", notes = "分页获取用户本人发起的活动")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "sponsor_id", value = "用户id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "page_num", value = "第几页", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "page_size", value = "页面数据的大小", required = true)
    })
    @RequestMapping(value = "/selectCreateMeetingList", method = RequestMethod.POST)
    public ResultBody selectCreateMeetingList(
            @RequestParam("sponsor_id") String sponsor_id,
            @RequestParam("page_num") Integer page_num,
            @RequestParam("page_size") Integer page_size
    ) {
        try {
            PageResult pageResult = activityService.selectCreateActivityList(sponsor_id, page_num, page_size);
            return new ResultBody(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "分页获取用户本人发起的活动失败！");
        }

    }

    @ApiOperation(value = "分页获取用户本人参与的活动", notes = "分页获取用户本人参与的活动")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "open_id", value = "微信唯一标识用户id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "page_num", value = "第几页", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "page_size", value = "页面数据的大小", required = true)
    })
    @RequestMapping(value = "/selectJoinActivityList", method = RequestMethod.POST)
    public ResultBody selectJoinActivityList(
            @RequestParam("open_id") String open_id,
            @RequestParam("page_num") Integer page_num,
            @RequestParam("page_size") Integer page_size
    ) {
        try {
            PageResult pageResult = activityService.selectJoinActivityList(open_id, page_num, page_size);
            return new ResultBody(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "分页获取用户本人参与的活动失败！");
        }

    }

    @ApiOperation(value = "获取所有用户本人发起的活动", notes = "获取所有用户本人发起的活动")
    @ApiImplicitParam(paramType = "query", dataType = "String", name = "sponsor_id", value = "用户id", required = true)
    @RequestMapping(value = "/selectAllCreateMeetingList/{sponsor_id}", method = RequestMethod.GET)
    public ResultBody selectCreateMeetingList(
            @PathVariable("sponsor_id") String sponsor_id
    ) {
        try {
            PageResult pageResult = activityService.selectCreateActivityList(sponsor_id, null, null);
            return new ResultBody(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "获取所有用户本人发起的活动失败！");
        }

    }

    @ApiOperation(value = "获取所有用户本人参与的活动", notes = "获取所有用户本人参与的活动")
    @ApiImplicitParam(paramType = "query", dataType = "String", name = "open_id", value = "微信唯一标识用户id", required = true)
    @RequestMapping(value = "/selectAllJoinActivityList/{open_id}", method = RequestMethod.GET)
    public ResultBody selectAllJoinActivityList(
            @PathVariable("open_id") String open_id
    ) {
        try {

            PageResult pageResult = activityService.selectJoinActivityList(open_id, null, null);
            return new ResultBody(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "获取所有用户本人参与的活动失败！");
        }

    }


    @ApiOperation(value = "获取所有活动类型", notes = "获取所有活动类型")
    @RequestMapping(value = "/selectAllTypeList", method = RequestMethod.GET)
    public ResultBody selectAllTypeList() {
        try {
            List<ActivityType> list = typeService.findAllTypeList();
            if (list == null) {
                return new ResultBody();
            }
            return new ResultBody(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "获取所有活动类型失败！");
        }

    }

    @ApiOperation(value = "获取所有该活动的参与者的信息", notes = "获取所有该活动的参与者的信息")
    @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "activity_id", value = "活动id", required = true)
    @RequestMapping(value = "/selectAllJoiner/{activity_id}", method = RequestMethod.GET)
    public ResultBody selectAllJoiner(
            @PathVariable("activity_id") Integer activity_id
    ) {
        try {
            //参与者集合
            List<UserDto> userDtos = new ArrayList<>();

            List<RegisterOrder> orderList = orderService.findOrderListWithActivityId(activity_id);
            if (orderList == null || orderList.size() <= 0) {
                return new ResultBody("500", "无人参加该活动");
            }
            for (RegisterOrder order : orderList) {

                String joiner_open_id = order.getOpen_id();
                if (joiner_open_id != null) {
                    RegisterUser user = userService.findByOpenId(joiner_open_id);
                    if (user != null) {
                        UserDto dto = new UserDto();
                        dto.setHead_image_url(user.getHead_image_url());
                        dto.setNickname(user.getNickname());
                        dto.setOpen_id(user.getOpen_id());
                        userDtos.add(dto);
                    }
                }
            }
            return new ResultBody(userDtos);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "获取所有该活动的参与者的信息失败！");
        }

    }

    @ApiOperation(value = "根据活动id查询活动信息", notes = "根据活动id查询活动信息")
    @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "activity_id", value = "活动id", required = true)
    @RequestMapping(value = "/selectActivity/{activity_id}", method = RequestMethod.GET)
    public ResultBody selectActivity(
            @PathVariable("activity_id") Integer activity_id
    ) {
        try {
            ActivityDetailBody activity = activityService.findByPrimaryKey(activity_id);
            if (activity != null) {
                return new ResultBody(activity);
            }
            return new ResultBody("500", "查询不到此活动！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "根据活动id查询活动信息失败！");
        }

    }
}
